package com.dfec.water.scheduled;

import com.dfec.component.uid.core.service.UidService;
import com.dfec.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.dfec.water.entity.YdbDeviceObserveEntity;
import com.dfec.water.entity.YdbDeviceTypeDictEntity;
import com.dfec.water.entity.YdbDeviceZsyEntity;
import com.dfec.water.entity.YdbWarnDeviceEntity;
import com.dfec.water.service.YdbDeviceObserveService;
import com.dfec.water.service.YdbDeviceTypeDictService;
import com.dfec.water.service.YdbDeviceZsyService;
import com.dfec.water.service.YdbWarnDeviceService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * @author trg
 * @description: TODO
 * @title: SyncWarnDeviceData
 * @projectName water-soil-conservation-serve
 * @email 1446232546@qq.com
 * @date 2025/2/25 10:43
 */
@Component
public class SyncWarnDeviceData {

    private final Logger logger = Logger.getLogger(SyncWarnDeviceData.class.getName());

    @Resource
    private YdbDeviceObserveService observeService;


    @Resource
    private YdbDeviceZsyService zsyService;

    @Resource
    private YdbDeviceTypeDictService deviceTypeDictService;

    @Resource
    private YdbWarnDeviceService warnDeviceService;

    @Resource
    private UidService uidService;


    /**
     * 自动监测设备数据是否有超过阈值的
     * 这个是计算每天的雨量累计值
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void syncWarnObserveDeviceData() {

        //获取到当天的数据
        YdbDeviceObserveEntity ydbDeviceObserveEntity = new YdbDeviceObserveEntity();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();

        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date endDate = calendar.getTime();
        Date[] dateRange = {startDate, endDate};
        ydbDeviceObserveEntity.setDateRange(dateRange);
        List<YdbDeviceObserveEntity> list = observeService.listAll(ydbDeviceObserveEntity);
        Map<Long, List<YdbDeviceObserveEntity>> collect = list.stream().collect(Collectors.groupingBy(YdbDeviceObserveEntity::getDeviceId));
        collect.forEach((key, value) -> {
            //每个设备分开统计
            if (list.isEmpty()) {
                logger.info("当天没有获取到设备数据");
                return;
            }
            double sumYljglj = list.stream()
                    .mapToDouble(entity -> {
                        try {
                            return Double.parseDouble(entity.getYljglj());
                        } catch (NumberFormatException e) {
                            logger.warning("无法解析 yljglj 字段: " + entity.getYljglj());
                            return 0.0;
                        }
                    })
                    .sum();
            logger.info("当天的 yljglj 总和为: " + sumYljglj);


            LambdaQueryWrapperX<YdbDeviceTypeDictEntity> qw = new LambdaQueryWrapperX<>();
            qw.eq(YdbDeviceTypeDictEntity::getCode, "6");
            YdbDeviceTypeDictEntity one = deviceTypeDictService.getOne(qw);
            Integer threshold = one.getThreshold();

            if (sumYljglj > threshold) {
                YdbDeviceObserveEntity ydbDeviceObserveEntity1 = list.get(0);
                logger.info("当前设备id为" + ydbDeviceObserveEntity1.getDeviceId() + "的zgsy设备数据超过阈值");
                YdbWarnDeviceEntity ydbWarnDeviceEntity = new YdbWarnDeviceEntity();
                ydbWarnDeviceEntity.setId(uidService.next());
                ydbWarnDeviceEntity.setDeviceId(ydbDeviceObserveEntity1.getDeviceId());
                ydbWarnDeviceEntity.setThreshold(threshold.toString());
                ydbWarnDeviceEntity.setActVal(sumYljglj + "");
                ydbWarnDeviceEntity.setWarnTime(new Date());
                ydbWarnDeviceEntity.setCreateTime(new Date());
                warnDeviceService.save(ydbWarnDeviceEntity);

            } else {
                logger.info("设备数据没有超过阈值");
            }
        });
    }

    /**
     * 蒸渗压设备数据是否有超过阈值的
     * 这个是根据渗透量去计算的
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void syncWarnZsyDeviceData() {
        LambdaQueryWrapperX<YdbDeviceTypeDictEntity> qw = new LambdaQueryWrapperX<>();
        qw.eq(YdbDeviceTypeDictEntity::getCode, "7");
        YdbDeviceTypeDictEntity one = deviceTypeDictService.getOne(qw);
        Integer threshold = one.getThreshold();
        YdbDeviceZsyEntity ydbDeviceZsyEntity = new YdbDeviceZsyEntity();
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, -5);
        Date fiveMinutesAgo = calendar.getTime();
        Date[] dateRange = {fiveMinutesAgo, date};
        ydbDeviceZsyEntity.setDateRange(dateRange);
        //获取最近五分钟的数据
        List<YdbDeviceZsyEntity> ydbDeviceZsyEntities = zsyService.listAll(ydbDeviceZsyEntity);
        if (ydbDeviceZsyEntities.isEmpty()) {
            logger.info("没有获取到蒸渗仪设备数据");
        }
        ArrayList<YdbWarnDeviceEntity> ydbWarnDeviceEntities = new ArrayList<>();
        ydbDeviceZsyEntities.forEach(item -> {
            if (item.getZslz() == null) {
                return;
            }
            String zslz = item.getZslz();
            if (zslz.startsWith("+")) {
                zslz = zslz.replace("+", "");
            }
            if (Integer.parseInt(zslz) > threshold) {
                logger.info("当前设备id为" + item.getDeviceId() + "的zgsy设备数据超过阈值");
                YdbWarnDeviceEntity ydbWarnDeviceEntity = new YdbWarnDeviceEntity();
                ydbWarnDeviceEntity.setId(uidService.next());
                ydbWarnDeviceEntity.setDeviceId(item.getDeviceId());
                ydbWarnDeviceEntity.setThreshold(threshold.toString());
                ydbWarnDeviceEntity.setActVal(zslz);
                ydbWarnDeviceEntity.setWarnTime(item.getTime());
                ydbWarnDeviceEntity.setCreateTime(new Date());
                ydbWarnDeviceEntities.add(ydbWarnDeviceEntity);
            }

        });
        warnDeviceService.saveBatch(ydbWarnDeviceEntities);

    }
}
